package database;

import java.sql.Connection;
import java.sql.SQLException;
import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;

public class DatabaseConnectionPool {
	private static final String URL = "jdbc:mysql://127.0.0.1:3306/express";
	private static final String DB_USER = "express";
	private static final String PASSWORD = "123";
	private static final int MIN_CONNECTIONS = 5;
	private static final int MAX_CONNECTIONS = 20;

	private static DatabaseConnectionPool dbcp = new DatabaseConnectionPool();

	private BoneCP connectionPool;

	public static DatabaseConnectionPool getInstance() {
		return dbcp;
	}

	private DatabaseConnectionPool() {
		initialize();
	}

	private void initialize() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}

		BoneCPConfig config = new BoneCPConfig();
		config.setJdbcUrl(URL);
		config.setUsername(DB_USER);
		config.setPassword(PASSWORD);
		config.setMinConnectionsPerPartition(MIN_CONNECTIONS);
		config.setMaxConnectionsPerPartition(MAX_CONNECTIONS);
		config.setPartitionCount(1);

		try {
			connectionPool = new BoneCP(config);
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public Connection getConnection() throws SQLException {
		return connectionPool.getConnection();
	}

	public void close() {
		connectionPool.shutdown();
	}
}


